<template>
  <layout>
    <u-navbar title="申请发票" :background="{ 'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)' }" :border-bottom="false" backIconColor="#fff" titleColor="#fff"></u-navbar>
    
    <view class="hint">温馨提示：电子发票与纸质发票具有同等效力</view>
    
    <u-form
      class="invoice-form"
      :model="form"
      ref="uForm"
      :error-type="['toast']"
      label-width="auto"
      :label-style="labelStyle">
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_ttleixing@2x.png" :left-icon-style="iconStyle" label="抬头类型" prop="type">
        <u-radio-group v-model="form.invoiceTitle.type" active-color="#FF5673">
          <u-radio disabled name="notCompany" icon-size="29" label-size="25">个人/非企业抬头</u-radio>
          <u-radio disabled name="company" icon-size="29" label-size="25">公司抬头</u-radio>
        </u-radio-group>
      </u-form-item>
      
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_fptaitou@2x.png" :left-icon-style="iconStyle" label="发票抬头" prop="invoiceTitle">
        <view v-if="!titleList.length" style="color: #6667FF;" @click="clickInvoiceTitle">抬头管理</view>
        <view v-else class="h-box justify-end" @click="showSelectTitle = true">
          <text class="pad-r-xs">{{ form.invoiceTitle.title }}</text>
          <image src="/static/img/right_arrow.png" mode="scaleToFill" style="width: 16rpx; height: 24rpx;"></image>
        </view>
        <u-select v-model="showSelectTitle" :list="titleList" default-value="[0]" value-name="_id" label-name="title" safe-area-inset-bottom @confirm="confirmInvoiceTitle"></u-select>
      </u-form-item>
      
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_leirong@2x.png" :left-icon-style="iconStyle" label="发票内容" prop="content">
        <view class="h-box justify-end" @click="showSelectContent = true">
          <text :class="{ 'pad-r-xs': true, 'gray': !form.content.text }">{{ form.content.text || '请选择发票内容' }}</text>
          <image src="/static/img/right_arrow.png" mode="scaleToFill" style="width: 16rpx; height: 24rpx;"></image>
        </view>
        <u-select v-model="showSelectContent" :list="contentList" default-value="[0]" value-name="_id" label-name="text" safe-area-inset-bottom @confirm="confirmContent"></u-select>
      </u-form-item>
      
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_jinqian@2x.png" :left-icon-style="iconStyle" label="开票金额">
        ￥{{ form.amount }}
      </u-form-item>
      
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_gengsuoxinx@2x.png" :left-icon-style="iconStyle" label="更多信息" prop="remark">
        <u-input v-model="form.remark" type="textarea" placeholder="请填写备注，地址等（非必填）" input-align="right" />
      </u-form-item>
      
      <u-form-item left-icon="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_jieshoufs@2x.png" :left-icon-style="iconStyle" label="接收方式" prop="email">
        <u-input v-model="form.email" type="text" placeholder="请输入邮箱地址" input-align="right" />
      </u-form-item>
    </u-form>
    
    <view @click="clickConfirm" class="confirm">确定</view>
    
    <view class="explain h-box justify-center">
      <text class="pad-r-xs">使用说明</text>
      <image src="/static/img/right_arrow.png" mode="scaleToFill" style="width: 16rpx; height: 24rpx;"></image>
    </view>
  </layout>
</template>

<script>
  const db = uniCloud.database()
  const dbCmd = db.command
  
  export default {
    name: 'invoice-apply',
    data() {
      return {
        idArr: [],
        
        contentList: [],
        showSelectContent: false,
        
        titleList: [],
        showSelectTitle: false,
        
        form: {
          invoiceTitle: {
            _id: null,
            title: ''
          },
          content: {
            _id: null,
            text: ''
          },
          amount: 0,
          remark: '',
          email: ''
        },
        rules: {
          'content._id': [
            {
              required: true,
              message: '请选择发票内容',
              trigger: ['blur', 'change']
            }
          ],
          email: [
            {
              required: true,
              message: '请填写邮箱地址',
              trigger: ['blur', 'change']
            },
            {
              pattern: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
              transform(value) {
                return String(value);
              },
              message: '请填写正确的邮箱地址'
            }
          ]
        },
        
        labelStyle: {
          fontSize: '29rpx'
        },
        iconStyle: {
          width: '36rpx',
          height: '36rpx',
          display: 'flex'
        }
      }
    },
    onLoad(e) {
      this.getOpenerEventChannel().on('data', res => {
        let data = JSON.parse(decodeURIComponent(res))
        this.form.amount = data?.money || 0
        this.idArr = data?.idArr || []
      })
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
      this.getData()
    },
    methods: {
      confirmInvoiceTitle(e) {
        this.form.invoiceTitle = {
          _id: e[0].value,
          title: e[0].label
        }
        let cache = this.titleList.find(item => item._id === e[0].value)
        this.form.invoiceTitle.type = cache.type
        this.form.invoiceTitle.number = cache.number
      },
      confirmContent(e) {
        this.form.content = {
          _id: e[0].value,
          text: e[0].label
        }
      },
      
      clickInvoiceTitle() {
        let that = this
        uni.navigateTo({
          url: `/pagesUser/platform/invoice-title-list`,
          events: {
            isUpdate: function(isUpdate) {
              if (!isUpdate) return
              that.getTitleList()
            }
          }
        })
      },
      clickConfirm() {
		  if (!this.form.invoiceTitle._id) {
		    uni.showToast({
		      title: '请先添加发票抬头',
		      icon: 'none'
		    })
		    return
		  }
        if (!this.form.content._id) {
          uni.showToast({
            title: '请选择发票内容',
            icon: 'none'
          })
          return
        }
        this.$refs.uForm.validate(async valid => {
          if (valid) {
            try{
              await db.collection('t3ds-invoice-record').add({
                status: 1,
                type: this.form.invoiceTitle.type,
                title: this.form.invoiceTitle.title,
                number: this.form.invoiceTitle.number,
                text: this.form.content.text,
                amount: this.form.amount,
                remark: this.form.remark,
                email: this.form.email,
                userId: this.$store.state.userInfo._id,
                createBy: this.$store.state.userInfo.nickname,
                orderIdArr: this.idArr
              })
              
              await db.collection('t3ds-order')
              .where({ '_id': dbCmd.in(this.idArr) })
              .update({ is_invoice: true })
              
              let that = this
              uni.hideLoading()
              uni.showToast({
                title: '保存成功',
                icon: 'none',
                success: () => {
                  setTimeout(function() {
                    that.getOpenerEventChannel().emit('isUpdate', true);
                    uni.navigateBack();
                  }, 1000);
                }
              })
            }catch(e){
              uni.hideLoading()
              uni.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          }
        });
      },
      
      async getTitleList() {
        let res = await this.$dbHelper.getList('t3ds-invoice-title', {
          showLoading: false,
          where: { userId: this.$store.state.userInfo._id },
          orderBy: 'isDefault desc',
          field: { '_id': true, 'title': true, 'type': true, 'number': true }
        })
        if (!res.length) return
        this.titleList = res
        this.form.invoiceTitle = this.titleList[0]
      },
      async getContentList() {
        let res = await this.$dbHelper.getList('t3ds-invoice-content', { showLoading: false })
        if (!res) return
        this.contentList = res
      },
      async getData() {
        uni.showLoading({ mask: true })
        
        try{
          await this.getTitleList()
          await this.getContentList()
        }catch(e){
          uni.hideLoading()
          console.error(e);
        }
        
        uni.hideLoading()
      }
    }
  }
</script>

<style>
  page {
    background-color: white;
  }
</style>

<style scoped lang="scss">
  .hint {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    color: #B7B7B7;
    background: #F5F5F5;
  }
  
  .invoice-form {
    .gray {
      color: rgb(192, 196, 204);
    }
    
    /deep/ .u-form-item {
      padding-left: 30rpx;
      padding-right: 30rpx;
      font-size: 25rpx !important;
      
      .u-form-item--left__content__icon {
        display: flex;
      }
      
      .u-form-item--right {
        text-align: right;
        
        .u-form-item--right__content__slot {
          justify-content: flex-end;
          
          .u-radio {
            margin-left: 20rpx;
            font-size: 25rpx !important;
            float: right !important;
            
            .u-radio__label:last-child {
              margin-right: 0;
            }
          }
        }
      }
    }
  }

  .confirm {
    width: 434rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 88rpx;
    font-size: 28rpx;
    background-color: #FF5673;
    text-align: center;
    color: white;
    margin: 0 auto;
    margin-top: 120rpx;
  }

  .explain {
    color: #969696;
    margin-top: 26rpx;
  }
</style>
